package com.jinhuhang.u2.invertmodule;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jinhuhang.u2.R;
import com.jinhuhang.u2.common.api.RetrofitUtils;
import com.jinhuhang.u2.common.base.activity.SimpleBaseActivity;
import com.jinhuhang.u2.common.constant.Constant;
import com.jinhuhang.u2.entity.Creaditor;
import com.jinhuhang.u2.entity.CreaditorItem;
import com.jinhuhang.u2.entity.CreatorApply;
import com.jinhuhang.u2.entity.InviteCode;
import com.jinhuhang.u2.listener.Listener;
import com.jinhuhang.u2.ui.BottomDialogManager;
import com.jinhuhang.u2.ui.MainActivity;
import com.jinhuhang.u2.ui.badge.MathUtil;
import com.jinhuhang.u2.ui.customview.CustomToast;
import com.jinhuhang.u2.util.MathUtils;
import com.jinhuhang.u2.util.StringUtils;
import com.jinhuhang.u2.util.http.HttpWrapperList;
import com.jinhuhang.u2.util.http.ResultList;
import com.jinhuhang.u2.util.http.T;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;

;

/**
 * Created by caoxiaowei on 2017/7/6.
 */
public class CreditorRightsTransferApplyActivity extends SimpleBaseActivity {


    boolean show = false;
    @Bind(R.id.back)
    ImageView mBack;
    @Bind(R.id.tv_title)
    TextView mTvTitle;
    @Bind(R.id.yelid_apply)
    TextView mYelidApply;
    @Bind(R.id.date_apply)
    TextView mDateApply;
    @Bind(R.id.month_apply)
    TextView mMonthApply;
    @Bind(R.id.value_apply)
    TextView mValueApply;
    @Bind(R.id.money_apply)
    TextView mMoneyApply;
    @Bind(R.id.coefficient_apply)
    TextView mCoefficientApply;
    @Bind(R.id.arrow_apply)
    ImageView mArrowApply;
    @Bind(R.id.price_apply)
    TextView mPriceApply;
    @Bind(R.id.cost_apply)
    TextView mCostApply;
    @Bind(R.id.img_check)
    ImageView mImgCheck;
    @Bind(R.id.check_apply)
    EditText mCheckApply;
    @Bind(R.id.trasferApply)
    TextView mTrasferApply;
    @Bind(R.id.refresh_apply)
    ImageView mRefreshApply;
    @Bind(R.id.lay1_apply)
    LinearLayout mLay1Apply;
    @Bind(R.id.title_app)
    TextView mTitleApp;
    private BottomDialogManager mBottomDialogManager;
    ArrayList<String> strings = new ArrayList<>();
    int id = 0;

    @Nullable
    @OnClick({R.id.lay1_apply, R.id.back, R.id.trasferApply, R.id.refresh_apply})
    public void onclick(View view) {
        switch (view.getId()) {
            case R.id.lay1_apply:
                mBottomDialogManager.show();
                break;
            case R.id.back:
                finish();
                break;
            case R.id.trasferApply:
                apply();
                break;
            case R.id.refresh_apply:
                requestImg();
                break;
        }
    }

    CreaditorItem data;
    int pos;

    @Override
    protected void initView() {
        super.initView();
        data = (CreaditorItem) getIntent().getSerializableExtra("data");
        if (data!=null) {
            mTitleApp.setText(data.getTitle());
            id = data.getTenderId();
            mYelidApply.setText(data.getApr() + "%");
            mDateApply.setText(data.getTimeLimit());
        }
        mTvTitle.setText("债权申请");
        for (int i = 1; i < 11; i++) {
            strings.add(i * 10 + "%");
        }
        mBottomDialogManager = new BottomDialogManager(this);
        mBottomDialogManager.setTitle("");
        mBottomDialogManager.setData(strings);
        //   mBottomDialogManager.setTextColor(R.color.itemtxt);
        mBottomDialogManager.setText("");
        mBottomDialogManager.setOkListener(new Listener.SelectOKListener() {
            @Override
            public void select(String select) {

                mCoefficientApply.setText(select);
                pos = strings.indexOf(select);
                float a =(float)(pos+1)/10;
                double b=MathUtils.add(mCreatorApply.getNoReceiveCaptial()+"",mCreatorApply.getNoReceiveInterestLastest()+"");
                mPriceApply.setText(MathUtils.multiply(String.valueOf(b),String.valueOf(a)).toString());
                mBottomDialogManager.dismiss();
            }
        });
        getData();
        requestImg();
        mPriceApply.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                try {
                    mCostApply.setText(String.format("%.2f", ((Double.parseDouble(mPriceApply.getText().toString())) * mCreatorApply.getFeeRatio() / 100)) + "元");
                } catch (Exception O) {

                }
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_creditor_apply;
    }

    private void apply() {

        if (StringUtils.isEmpty(mCheckApply.getText().toString())) {
            CustomToast.showToast("请输入验证码！");
            return;
        }
        double m = StringUtils.isEmpty(mPriceApply.getText().toString()) ? 0 : Double.parseDouble(mPriceApply.getText().toString());
        showDialog(null);
        Map<String, String> map = new HashMap<>();
        map.put("userId", MainActivity.uid);
        map.put("actualAccount", String.valueOf(m));
        if (mCreatorApply.getIsForceAll() == 1) {
            map.put("ratio", String.valueOf(100));
        } else {
            map.put("ratio", String.valueOf((pos + 1) * 10));
        }

        map.put("randomCode", String.valueOf(mCheckApply.getText().toString()));

        Intent intent = new Intent(this, ResultActivity.class);
//         intent.putExtra("type", Constant.tender_success);
//         intent.putExtra("title", data.getTitle());
//         intent.putExtra("apr", data.getApr()+"");
//         intent.putExtra("term", data.getTimeLimit()+"");
//         intent.putExtra("money",String.valueOf(m));
//             intent.putExtra("dikou", "");
//             intent.putExtra("jiaxi", "");

        addSubscription(RetrofitUtils.getInstance().build()
                .transferApply(map)
                .compose(T.defaultScheduler())
                .subscribe(new ResultList<HttpWrapperList<Creaditor>>() {

                    @Override
                    protected void onSuccess(HttpWrapperList<Creaditor> data) {
                        if (data.code == Constant.SUCCESS_CODE) {
                            intent.putExtra(ResultActivity.typestr, Constant.zhaizhuan_success);
                        } else {
                            intent.putExtra(ResultActivity.typestr, Constant.zhaizhuan_fail);
                        }
                        dissDialog();
                        startActivity(intent);
                    }

                    @Override
                    protected void onFaild() {
                        super.onFaild();
                        dissDialog();
                    }
                }));
    }

    protected void getData() {
        addSubscription(RetrofitUtils.getInstance().build()
                .transferApplyDetail(MainActivity.uid, id)
                .compose(T.defaultScheduler())
                .subscribe(new ResultList<HttpWrapperList<CreatorApply>>() {

                    @Override
                    protected void onSuccess(HttpWrapperList<CreatorApply> data) {
                        if (data.code == Constant.SUCCESS_CODE) {
                            showData(data.getSingleData());
                        } else {

                        }
                    }
                }));
    }

    CreatorApply mCreatorApply;

    private void showData(CreatorApply data) {
        mCreatorApply = data;
        mMonthApply.setText(data.getRemainMsg());
        if ((data.getNoReceiveCaptial() + data.getNoReceiveInterestLastest()) > 0) {
            mValueApply.setText((data.getNoReceiveCaptial() + data.getNoReceiveInterestLastest()) + "元");
        }
        if (data.getNoReceiveCaptial() > 0) {
            mMoneyApply.setText(data.getNoReceiveCaptial() + "元");
        }
        if (data.getIsForceAll() == 1) {
            mLay1Apply.setEnabled(false);
            mArrowApply.setVisibility(View.GONE);
            mPriceApply.setEnabled(false);
        }

        mPriceApply.setText((data.getNoReceiveCaptial() + data.getNoReceiveInterestLastest()) + "");
        mCostApply.setText(String.format("%.2f", (data.getNoReceiveCaptial() + data.getNoReceiveInterestLastest()) * data.getFeeRatio() / 100) + "元");
    }

    private void requestImg() {

        addSubscription(RetrofitUtils.getInstance().build()
                .getCheckImg(MainActivity.uid)
                .compose(T.defaultScheduler())
                .subscribe(new ResultList<HttpWrapperList<InviteCode>>() {

                    @Override
                    protected void onSuccess(HttpWrapperList<InviteCode> data) {
                        if (data.code == Constant.SUCCESS_CODE) {
                            byte[] decodeBytes = Base64.decode(data.getSingleData().getImage().getBytes(), Base64.NO_WRAP);
                            Bitmap bmp = BitmapFactory.decodeByteArray(decodeBytes, 0, decodeBytes.length);
                            mImgCheck.setImageBitmap(bmp);
                        } else {

                        }
                    }

                    @Override
                    protected void onFaild() {
                        super.onFaild();
                    }
                }));

    }
}
